package com.test45_JUC;

import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadFactory;

/**
 * ThreadFactory，线程工厂接口
 */
public class Demo02_ThreadFactory {

    public static void main(String[] args) {
        // test1();
        test2();
    }

    /**
     * 传统方式创建线程
     */
    public static void test1() {
        for (int x = 0; x < 100; x++) {
            new Thread(() -> {
                System.out.println("线程名称：" + Thread.currentThread().getName());
            }).start();
        }
    }

    /**
     * 通过线程工厂类创建线程
     */
    public static void test2() {
        for (int x = 0; x < 10; x++) {
            Thread thread = YootkThreadFactory.getInstance().newThread(() -> {
                System.out.println("多线程执行：" + Thread.currentThread().getName());
            });
            thread.start();
        }
    }
}

/**
 * 创建线程工厂类
 */
class YootkThreadFactory implements ThreadFactory {
    private static ThreadFactory INSTANCE = new YootkThreadFactory();
    private static final String TITLE = "yootk-";   // 定义线程名称的开头
    private static int count = 0;   // 线程的自动计数处理

    // 构造方法私有化
    private YootkThreadFactory() {
    }

    // 返回工厂实例
    public static ThreadFactory getInstance() {
        return INSTANCE;
    }

    /*@Override
    public Thread newThread(Runnable r) {
        return new Thread(r, TITLE + count++);
    }*/

    // 使用反射机制进行线程创建
    @Override
    public Thread newThread(Runnable r) {
        try {
            Class<?> clazz = Class.forName("java.lang.Thread");
            Constructor<?> constructor = clazz.getConstructor(Runnable.class, String.class);
            return (Thread) constructor.newInstance(r, TITLE + count++);
        } catch (Exception e) {
            return null;
        }
    }
}